import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { getUserInfo } from '@/http/api'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: '首页',
        component: () => import(/* webpackChunkName: "Index" */ '../views/Index')
      },
      {
        path: '/logistics',
        name: '物流单',
        component: () => import(/* webpackChunkName: "logistics" */ '../views/Logistics')
      },
      {
        path: '/deliveryForm',
        name: '送货单',
        component: () => import(/* webpackChunkName: "deliveryForm" */ '../views/DeliveryForm')
      },
      {
        path: '/myClient',
        name: '我的客户',
        component: () => import(/* webpackChunkName: "myClient" */ '../views/MyClient')
      },
      {
        path: '/visit',
        name: '走访',
        component: () => import(/* webpackChunkName: "visit" */ '../views/Visit')
      },
      {
        path: '/personal',
        name: '个人中心',
        component: () => import(/* webpackChunkName: "personal" */ '../views/Personal')
      },
      {
        path: '/msg',
        name: '信息中心',
        component: () => import(/* webpackChunkName: "msg" */ '../views/Msg')
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login')
  }
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})
// 获取用户的信息
async function getUserInfoFn() {
  let res = await getUserInfo();
  store.commit('getUserInfo', res.data)
}
// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  let token = sessionStorage.getItem('token');
  // 判断用户是否登录
  if (!token && to.path != "/login") {
    next('/login')
  } else if (!token && to.path == "/login") {
    next()
  } else {
    getUserInfoFn();
    setTimeout(() => {
      next()
    }, 400)
  }
})

export default router
